﻿using System;
using System.Linq;
using iss.sg4210.se18.team6s.jass.DAL;
using iss.sg4210.se18.team6s.jass.DAL.DataAccess.Interfaces;

namespace iss.sg4210.se18.team6s.jass.BL
{
    public class CompanyFacade
    {
        ICompany companyRepo = null;

        public CompanyFacade()
        {
            companyRepo = DataAccessFactory.Instance.Company;
        }

        public IQueryable<Company> FindAllCompanies()
        {
            try
            {
                return companyRepo.FindAllCompanies();
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_RETRIEVE, ex);
            }
        }

        public Company GetCompany(int id)
        {
            try
            {
                return companyRepo.GetCompany(id);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_RETRIEVE, ex);
            }
        }

        public void AddCompany(Company c)
        {
            IQueryable<Company> companies = FindAllCompanies();
            if (companies.Count(m => m.Name == c.Name) > 0)
                throw new JASSException("Duplicate Company with same Title '" + c.Name + "' found!");

            try
            {
                companyRepo.AddCompany(c);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_SAVE, ex);
            }
        }

        public void UpdateCompany(Company c)
        {
            try
            {
                companyRepo.UpdateCompany(c);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_UPDATE, ex);
            }
        }

        public void DeleteCompany(int id)
        {
            Company company = GetCompany(id);
            if (company.Advertisements.Count > 0)
                throw new JASSException("Cannot delete Company '" + company.Name + "'. It has one or more Advertisements!");

            try
            {
                companyRepo.DeleteCompany(id);
            }
            catch (Exception ex)
            {
                throw new JASSException(JASSConstants.JASS_ERROR_DELETE, ex);
            }
        }
    }
}
